package com.zh.note.huawei.twohundred.仿LISP运算;

import java.util.Stack;

/**
 * https://dream.blog.csdn.net/article/details/130907036
 */
public class Main {
    public static void main(String[] args) {
        Stack<String> stack = new Stack<>();
        Stack<Integer> res = new Stack<>();
        String str = "(add 1 (div -7 31))";

        int len = str.length();
        // 1 从后往前一次把特殊字添加到栈中
        for (int i = len - 1; i >= 0; ) {
            if (str.charAt(i) == ')' || str.charAt(i) == ' ' || str.charAt(i) == '(') {
                i = i - 1;
            } else if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z') { // 遇到的是字母
                String op = str.substring(i - 2, i + 1);
                stack.push(op);
                i -= 3;
            } else {
                // 遇到数字
                int spaceIndex = str.lastIndexOf(' ', i);
                if (spaceIndex < 0 || (str.charAt(spaceIndex + 1) <= 'z' && str.charAt(spaceIndex + 1) >= 'a')) {
                    spaceIndex = str.lastIndexOf('(', i);
                }
                String num = str.substring(spaceIndex + 1, i + 1);
                stack.push(num);
                i = spaceIndex;

            }
        }
        boolean flag = true;
        int n = stack.size();
        for (int i = 0; i < n; i++) {
            String s = stack.get(i);
            if (s.equals("add") || s.equals("sub") || s.equals("mul") || s.equals("div")) {
                if (res.size() < 2) {
                    return;
                }
                int num2 = res.pop();
                int num1 = res.pop();
                int result = 0;
                if (s.equals("add")) {
                    result = num1 + num2;
                } else if (s.equals("sub")) {
                    result = num2 - num1;
                } else if (s.equals("mul")) {
                    result = num1 * num2;
                } else if (s.equals("div")) {
                    if (num1 == 0) {
                        flag = false; // 分母为0
                    } else {
                        result = num2 / num1;
                        if (result < 0) {
                            result -= 1;
                        }
                    }
                }
                res.push(result);
            } else { // 不是操作，则把数字放到res中
                res.push(Integer.parseInt(s));
            }
        }
        if (!flag) {
            System.out.println("error");
        } else {
            System.out.println(res.peek());
        }
    }
}
